<template>
<div>
  <div class="priceBox">
    <div class="priceItem">
      <div class="pad-box1">
        <div class="border_b dis-flex fieldItem flex-y-center" @tap.stop="checkIsUse">
          <div class="label">零售价</div>
          <div class="contentBox dis-flex flex-y-center">
            <div class="content onelist-hidden">
              <!-- <text v-if="priceData.goods_price == ''">必填</text>
              <text v-else :class="currentTab == '1' && checkLabel != '' ? '' : 'col-3'">{{priceData.goods_price}}</text> -->
				      <input type="digit" placeholder-class="place-holder" @input="openItem('goods_price')" :disabled="currentTab == '1' && checkLabel != ''" placeholder="必填" v-model="priceData.goods_price" :maxlength="field.goods_price.maxlength"/>
            </div>
            <div class="tips1">
              元
            </div>
          </div>
        </div>
      </div>
      <div class="pad-box1">
        <div class="dis-flex fieldItem flex-y-center" :class="priceSet ? 'border_b' : ''" @tap="changePriceSet()">
          <div class="label">其他</div>
          <div class="contentBox dis-flex flex-y-center">
            <div class="content onelist-hidden"></div>
            <div class="tips tips1">
              <div class="tipIconBox" :class="priceSet ? 'transIcon' : ''">
                <text class="tipIcon iconfont2 icon-gengduobeifen2"></text>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="priceItem" v-show="priceSet">
      <div class="pad-box1">
        <div class="border_b dis-flex fieldItem flex-y-center" @tap.stop="checkIsUse">
          <div class="label">划线价</div>
          <div class="contentBox dis-flex flex-y-center">
            <div class="content onelist-hidden">
              <!-- <text v-if="priceData.line_price == ''"></text>
              <text v-else  :class="currentTab == '1' && checkLabel != '' ? '' : 'col-3'">{{priceData.line_price}}</text>
               -->
				      <input type="digit" placeholder-class="place-holder" @input="openItem('line_price')" :disabled="currentTab == '1' && checkLabel != ''" v-model="priceData.line_price" :maxlength="field.line_price.maxlength"/>
            </div>
            <div class="tips1">
              元
            </div>
          </div>
        </div>
      </div>
      <div class="pad-box1">
        <div class="border_b dis-flex fieldItem flex-y-center">
          <div class="label">库存</div>
          <div class="contentBox dis-flex flex-y-center">
            <div class="content onelist-hidden">
              <!-- <text v-if="priceData.stock_num == ''">必填</text>
              <text v-else class="col-3">{{priceData.stock_num}}</text> -->
				      <input type="number" placeholder-class="place-holder" @input="openItem('stock_num')" placeholder="必填" v-model="priceData.stock_num" :maxlength="field.stock_num.maxlength"/>
            </div>
          </div>
        </div>
      </div>
      <div class="pad-box1">
        <div class="dis-flex fieldItem flex-y-center">
          <div class="label">重量</div>
          <div class="contentBox dis-flex flex-y-center">
            <div class="content onelist-hidden">
              <!-- <text v-if="priceData.goods_weight == ''">非必填，默认0.1</text>
              <text class="col-3">{{priceData.goods_weight}}</text> -->
				      <input type="digit" placeholder-class="place-holder" @input="openItem('goods_weight')" placeholder="非必填，默认0.1" v-model="priceData.goods_weight" :maxlength="field.goods_weight.maxlength"/>
            </div>
            <div class="tips1">
                kg
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="pad-box specBox dis-flex flex-y-center">
    <div class="specButBox dis-flex flex-y-center">
      <div class="butBox addSpec" @tap.stop="addSpec">
        <text class="iconfont2 icon-jiahao"></text>
        规格
      </div>
      <!-- <picker class="haveSpec" @change="tempListChange($event)" :range="tempList">
        模板
      </picker> -->
      <picker class="historySpec" @change="historyListChange($event, 'history')" :range="historyList" range-key="spec_name">
        历史
      </picker>
      <picker class="historySpec" @change="historyListChange($event, 'recommend')" :range="recommendList" range-key="spec_name">
        推荐
      </picker>
      <div class="addSpecTips" @tap.stop="showTip1">
        <text class="iconfont2 icon-juxing"></text>
      </div>
    </div>
  </div>
  <div class="pad-box2 specList">
    <div class="listItem dis-flex" v-for="(item, index) in specListNew" :key="index">
      <div class="label">{{item.label}}</div>
      <div class="content">
        <div class="spec" v-for="(items, indexs) in item.list" :key="indexs" :class="items.checked ? 'checked' : ''" @tap.stop="checked(index, indexs)">
          {{items.label}}
          <text class="iconBox iconfont2 icon-shanchu2" @tap.stop="delChild(index, indexs)"></text>
        </div>
        <div class="addSpec spec" @tap.stop="addChildSpec(item)">
          <text class="iconfont2 icon-jiahao"></text>子规格
        </div>
      </div>
      <div class="delSpecBox" @tap.stop="delSpec(index)">
        <div class="delSpec"></div>
      </div>
    </div>
  </div>
  <popup :show="showPopup" @clickmask="clickmask">
    <view class="popup-main">
      <view class="pop-close" @tap="clickmask"><text class="iconfont2 icon-shanchu1"></text></view>
      <view class="poptitle">确认删除所选规格？</view>
      <view class="pop-input">
        规格删除之后将不能恢复
      </view>
			<view class="pop-btn">
				<view @tap="clickmask">取消</view>
				<view @tap="confirm">确认</view>
			</view>
    </view>
  </popup>
  <popup :show="showPopup1" @clickmask="clickmask1">
    <view class="popup-main1">
      <view class="pop-close" @tap.stop="clickmask1"><text class="iconfont2 icon-shanchu1"></text></view>
      <view class="poptitle">提示</view>
      <view class="pop-input">
        1、新增规格分为“多规格同价”和多规格异价 两类，“多规格同价”不可更改“零售价”和“划 线价”，“多规格异价”可选择更改“零售价” 和“划线价”。<br>
        2、可自主添加规格，也可使用模版添加规格 自主添加规格将记录在历史规格内。<br>
        3、规格可编辑可删除，删除后将不能恢复。<br>
      </view>
			<view class="pop-btn">
				<view @tap.stop="clickmask1">我知道了</view>
			</view>
    </view>
  </popup>
  <popup-input :title="inputTitle" :inputType="inputType" :placeholder="placeholder" ref="popupInput" :maxlength="maxlength"></popup-input>
  <popup-inputs :title="inputTitle" :inputType="inputType" :placeholder="placeholder" ref="popupInputs" :maxlength="maxlength"></popup-inputs>
</div>
</template>

<script>
const App = getApp().globalData;
import popup from '@/components/popup/index';
import popupInput from '@/components/popup-input/index';
import popupInputs from './popup-inputs/index';

export default {
  data() {
    return {
		currentTab: 0,
      priceSet: false,
      inputType: 'text',
      inputTitle: '新增规格',
      placeholder: '例如：颜色、尺码',
      maxlength: '-1',
      showPopup: false,
      showPopup1: false,
      next: null,
      priceData: {
        goods_price: '',
        line_price: '',
        stock_num: '100',
        goods_weight: ''
      },
      specListNew: [],
      priceList: [],
      checkLabel: '',
      // 模板列表
      tempList: [
        '模板1',
        '模板2'
      ],
      tempIdList: [
        {
          label: '模板1',
          list: [{
            label: '模板11'
          }, {
            label: '模板12'
          }]
        },
        {
          label: '模板2',
          list: [{
            label: '模板21'
          }, {
            label: '模板22'
          }]
        },
      ],
      // 历史列表
      historyList: [
      ],
      // 推荐
      recommendList: [],
      field: {
        // 零售价
        goods_price: {
          type: 'text',
          name: '零售价',
          fieldName: 'goods_price',
          maxlength: '9'
        },
        // 划线价
        line_price: {
          type: 'text',
          name: '划线价',
          fieldName: 'line_price',
          maxlength: '9'
        },
        // 库存
        stock_num: {
          type: 'text',
          name: '库存',
          fieldName: 'stock_num',
          maxlength: '9'
        },
        goods_weight: {
          type: 'text',
          name: '重量',
          fieldName: 'goods_weight',
          maxlength: '9'
        },
      }
    };
  },

  components: {
    popup,
    popupInput,
    popupInputs
  },
  lifetimes: {
    // 组件生命周期声明对象，将组件的生命周期收归到该字段进行声明，原有声明方式仍旧有效，如同时存在两种声明方式，则lifetimes字段内声明方式优先级最高
    attached() {
      this.currentTab = this.currentTabs
    }
  },
    observers: {
      'currentTabs': function(currentTab) {
        // 在 rate被设置时，执行这个函数
		console.log(currentTab)
        this.currentTab = currentTab
      }
    },
  props: {
    currentTabs: {
      type: [String, Number],
      default: ''
    }
  },
  watch:{
	  currentTabs(val) {
        this.currentTab = val
	  }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  created() {
	 this.currentTab = this.currentTabs
    this.getHistoryList()
  },
  methods: {
    changePriceSet() {
      this.priceSet = !this.priceSet
    },
    getHistoryList() {
      App._get('shop.wxapp.goods/add', {}, (result) => {
        if (result.code == '1') {
          this.historyList = result.data.specList.common || []
          this.recommendList = result.data.specList.recommend || []
        } else {
          this.historyList = []
          this.recommendList = []
        }
      })
    },
    specListUpdata(data) {
      if (this.priceData.goods_price == '' && this.priceData.line_price == '' && this.priceData.stock_num == 100 && this.priceData.goods_weight == '' || this.currentTab == '2') {
        this.priceData = {
          goods_price: data.goods_price || '',
          line_price: data.line_price || '',
          stock_num: data.stock_num || 100,
          goods_weight: data.goods_weight || ''
        }
        this.priceList.forEach(item => {
            item.goods_price = data.goods_price || ''
            item.line_price = data.line_price || ''
            item.stock_num = data.stock_num || 100
            item.goods_weight = data.goods_weight || ''
        })
      }
      this.uniCheckLabel()
    },
    updataPrice(fieldName, val) {
      this.priceList.forEach(item => {
        if (this.currentTab == '2') {
          if (item[fieldName] == '') {
            item[fieldName] = val
          }
        } else {
          item[fieldName] = val
        }
      })
    },
    updata(data) {
      let specListNew = []
      let priceList = []
      data.spec_attr.forEach(item => {
        specListNew.push({
          spec_id: item.group_id,
          label: item.group_name,
          list: this.unitSpecItems(item.spec_items)
        })
      })
      data.spec_list.forEach(item => {
        priceList.push({
          item_id: item.spec_sku_id,
          goods_price: item.form.goods_price,
          line_price: item.form.line_price,
          stock_num: item.form.stock_num,
          goods_weight: item.form.goods_weight
        })
      })
      this.specListNew = specListNew
      this.priceList = priceList
	  let time = setInterval(() => {
		  console.log(this.currentTab)
		  if (this.currentTab) {
			  if (this.currentTab == '1' && priceList.length > 0) {
				let priceData = priceList[0]
				this.priceData.goods_price = priceData.goods_price
				this.priceData.line_price = priceData.line_price
				this.priceData.stock_num = priceData.stock_num
				this.priceData.goods_weight = priceData.goods_weight
			  }
			  this.uniCheckLabel()
			  clearInterval(time)
		  }
	  }, 10)
    },
    unitSpecItems(list) {
      let newList = []
      list.forEach((item, index) => {
        let obj = {
          label: item.spec_value,
          spec_value_id: item.item_id
        }
        if (this.currentTab == 2 && index == 0) {
          obj.checked = true
        } else {
          obj.checked = false
        }
        newList.push(obj)
      })
      return newList
    },
    submit() {
      let specListNew = []
      this.specListNew.forEach(item => {
        let list = []
        item.list.forEach(items => {
          list.push({
            item_id: items.spec_value_id,
            spec_value: items.label
          })
        })
        let data = {
          group_id: item.spec_id,
          group_name: item.label,
          spec_items: list
        }
        specListNew.push(data)
      })
      let priceList = []
      this.priceList.forEach((item, index) => {
        let rows = []
        let item_id = item.item_id.split('_')
        item_id.forEach((element, indexs) => {
          specListNew.forEach(items => {
            items.spec_items.forEach(itemObj => {
              if (element == itemObj.item_id) {
                rows.push({
                  rowspan: indexs,
                  item_id: element,
                  spec_value: itemObj.spec_value
                })
              }
            })
          })
        })
        let data = {
          spec_sku_id: item.item_id,
          rows: rows,
          form: {
            stock_num: item.stock_num,
            line_price: item.line_price,
            goods_price: item.goods_price,
            goods_weight: item.goods_weight || '0.1'
          }
        }
        priceList.push(data)
      })
      return {
        spec_attr: specListNew,
        spec_list: priceList
      }
    },
    // 模板选择
    tempListChange(e) {
      this.specListNew.push(this.tempIdList[e.detail.value])
      this.priceList = this.uniPrice(this.specListNew)
    },
    // 历史选择
    historyListChange(e, type) {
      let item = {}
      if (type == 'recommend') {
        item = this.recommendList[e.detail.value]
      }  else if (type == 'history') {
        item = this.historyList[e.detail.value]
      }
      let isHave = false
      this.specListNew.forEach(items => {
        if (items.label == item.spec_name) {
          isHave = true
        }
      })
      if (isHave) {
        App.showError('与其他规格重复，请重新添加！')
        return false
      }

      let list = []
      item.spec_value ? item.spec_value.forEach((items, index) => {
        let obj = {
          label: items.spec_value,
          spec_value_id: items.spec_value_id,
          checked: false
        }
        if (this.currentTab == 2 && index == 0) {
          obj.checked = true
        }
        list.push(obj)
      }) : ''
      let obj = {
          spec_id: item.spec_id,
          label: item.spec_name,
          list: list
      }
      this.specListNew.push(obj)
      this.priceList = this.uniPrice(this.specListNew)
    },
    checkIsUse() {
      console.log(111111111)
      if (this.currentTab == '1') {
        if (this.checkLabel != ''){
          this.$api.msg('多规格同价不可修改单规格价格！')
        }
      }
    },
    openItem(fieldName) {
      let isHave = false
      this.priceList.forEach((item) => {
        if (item.item_id == this.checkLabel) {
          item[fieldName] = this.priceData[fieldName]
          isHave = true
        }
      })
      if (!isHave) {
        this.priceList.forEach((item) => {
          item[fieldName] = this.priceData[fieldName]
        })
      }
    },
    //  选中规格
    checked(index, indexs) {
      this.specListNew[index].list.forEach((element, newIndex) => {
        if (indexs == newIndex) {
          element.checked = !element.checked
        } else {
          element.checked = false
        }
      });
      this.uniCheckLabel()
    },
    uniCheckLabel() {
      let spec_value_ids = []
      this.specListNew.forEach((element => {
        let isCheck = false
        element.list.forEach(item => {
          if (item.checked) {
            if (this.currentTab == 1) {
              item.checked = false
            } else if (this.currentTab == 2) {
              isCheck = true
              spec_value_ids.push(item.spec_value_id)
            }
          }
        })
        if (!isCheck && this.currentTab == 2) {
          if (element.list[0]) {
            element.list[0].checked = true
            spec_value_ids.push(element.list[0].spec_value_id)
          }
        }
      }))
      this.checkLabel = spec_value_ids.join('_')
      this.priceList = this.uniPrice(this.specListNew)
      this.priceList.forEach((item) => {
        if (item.item_id == this.checkLabel) {
          this.priceData = {
            goods_price: item.goods_price,
            line_price: item.line_price,
            stock_num: item.stock_num,
            goods_weight: item.goods_weight
          }
        }
      })
    },
    // 处理价格列表
    uniPrice(list) {
      let newList = []
      let array = []
      list.forEach(item => {
        let itemList = []
        item.list.forEach(items => {
          itemList.push(items)
        })
        array.push(itemList)
      })
      if (array.length < 2) {
        let newArr = []
        array.forEach(item => {
          item.forEach(items => {
            let list = []
            list.push(items)
            newArr.push(list)
          })

        })
        newList = newArr || [];
      } else {
        newList = [].reduce.call(array, (col, set) => {
          var res = [];
          col.forEach((c) => {
              set.forEach((s) => {
                  var t = [].concat(Array.isArray(c) ? c : [c]);
                  t.push(s);
                  res.push(t);
              })
          });
          return res;
        });
      }
      let arr = []
      newList.forEach(item => {
        let item_ids = []
        item.forEach(items => {
          item_ids.push(items.spec_value_id)
        })
        
        arr.push({
          item_id: item_ids.join('_'),
          goods_price: this.priceData.goods_price,
          line_price: this.priceData.line_price,
          stock_num: this.priceData.stock_num,
          goods_weight: this.priceData.goods_weight
        })
      })
      arr.forEach(item => {
        this.priceList.forEach(items => {
          if (item.item_id == items.item_id) {
            item.goods_price = items.goods_price
            item.line_price = items.line_price
            item.stock_num = items.stock_num
            item.goods_weight = items.goods_weight
          }
        })
      })
      return arr
    },
    // 新增规格
    addSpec() {
      this.inputTitle = '新增规格'
      this.placeholder = '例如：颜色、尺码'
      this.inputType = 'text'
      this.maxlength = '-1'
      this.$refs.popupInput._open('', (val) => {
        if (val && val != 0) {
          let isHave = false
          this.specListNew.forEach(items => {
            if (items.label == val) {
              isHave = true
            }
          })
          if (isHave) {
            App.showError('与其他规格重复，请重新添加！')
            return false
          }
          App._post_form('shop.goods.spec/addSpec', {
            spec_name: val
          }, (result) => {
            this.specListNew.push({
              label: val,
              spec_id: result.data.spec_id,
              list: []
            })
            this.priceList = this.uniPrice(this.specListNew)
          })
        }
      })
    },
    // 新增规格
    addChildSpec(item) {
      this.inputTitle = '新增子规格'
      this.placeholder = '例如：白色、黑色、S、M'
      this.inputType = 'text'
      this.maxlength = '-1'
      this.$refs.popupInputs._open('', (val, next) => {
        if (val && val != '') {
          let isHave = false
          item.list.forEach(items => {
            if (items.label == val) {
              isHave = true
            }
          })
          if (isHave) {
            App.showError('与其他子规格重复，请重新添加！')
            return false
          }
          App._post_form('shop.goods.spec/addSpecValue', {
            spec_value: val,
            spec_id: item.spec_id
          }, (result) => {
            item.list.push({
              label: val,
              spec_value_id: result.data.spec_value_id,
              checked: false
            })
            this.priceList = this.uniPrice(this.specListNew)
            this.uniCheckLabel()
            next()
          })
        }
      })
    },
    // 打开提示框
    showTip(next) {
      this.showPopup = true
    },
    // 打开提示框
    showTip1(next) {
      this.showPopup1 = true
    },
    // 关闭提示框
    clickmask() {
      this.showPopup = false
    },
    clickmask1() {
      this.showPopup1 = false
    },
    confirm() {
      this.next()
      this.next = null
      this.clickmask()
    },
    // 删除规格
    delSpec(index) {
      this.next = () => {
        this.specListNew[index].list.forEach(item => {
          if (item.label == this.checkLabel) {
            this.checkLabel = ''
          }
        })
        this.specListNew.splice(index, 1)
        this.uniCheckLabel()
      }
      this.showTip()
    },
    // 删除子规格
    delChild(index, childIndex) {
      if (this.specListNew[index].list[childIndex].label == this.checkLabel) {
        this.checkLabel = ''
      }
      this.specListNew[index].list.splice(childIndex, 1)
      this.uniCheckLabel()
    }
  }
};
</script>
<style lang="scss">
@import "../index.scss";
@import "./index.scss";
</style>